package com.gxp.util.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import com.gxp.util.common.GXPUtil;

public class MyAccessDeniedHandlerImpl implements AccessDeniedHandler {

	private String accessDeniedUrl;

	public MyAccessDeniedHandlerImpl() {

	}

	public String getAccessDeniedUrl() {
		return accessDeniedUrl;
	}

	public void setAccessDeniedUrl(String accessDeniedUrl) {
		this.accessDeniedUrl = accessDeniedUrl;
	}

	public MyAccessDeniedHandlerImpl(String accessDeniedUrl) {
		this.accessDeniedUrl = accessDeniedUrl;
	}

	@Override
	public void handle(HttpServletRequest req, HttpServletResponse resp,
			AccessDeniedException reason) {

		PrintWriter out = null;
		try {
			boolean isAjax = "XMLHttpRequest".equals(req
					.getHeader("X-Requested-With"));

			if (isAjax) {
				String jsonObject = GXPUtil.getJsonString("Message.error.403", true, "");				
				String contentType = "application/json";
				resp.setContentType(contentType);
				out = resp.getWriter();
				out.print(jsonObject);
				out.flush();
				
				return;
			} else {
				String path = req.getContextPath();
				String basePath = req.getScheme() + "://" + req.getServerName()
						+ ":" + req.getServerPort() + path + "/";

				resp.sendRedirect(basePath + accessDeniedUrl);

			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
				out = null;
			}
		}
	}

}
